package com.marketingexpert.controller.personmgnt;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.marketingexpert.config.Configuration;
import com.marketingexpert.dao.AuthorityDao;
import com.marketingexpert.domain.User;
import com.marketingexpert.domain.UserType;
import com.marketingexpert.domain.permission.UserRole;
import com.marketingexpert.service.usermgnt.UserService;
import com.marketingexpert.util.Resources;
import com.marketingexpert.util.WebUtils;

public class WeiboAddCheckController implements Controller {

	private static Logger logger = Logger
			.getLogger(WeiboAddCheckController.class);

	private AuthorityDao authorityDao;

	private UserService userService;

	private Configuration configuration;

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String parentUserId = (String) request.getSession().getAttribute("parentUserId");
		UserRole ur = authorityDao.getUserRole(parentUserId);

		String callUrl = request.getParameter("callUrl");
		String oauthSrc = request.getParameter("oauthSrc");
		
		if(ur.getRoleId() == Integer.parseInt(configuration.getTryer_RoleId())) {
			if(!oauthSrc.equals("sina")) {
				request.getSession().setAttribute("authorityLimitInfo", Resources.getString("TryUserAddWeiboLimitTencent"));
				response.sendRedirect(WebUtils.getBasepath(request) + "/pages/authorityLimit.jsp");
				return null;
			}
			
			List<User> weiboUsers = userService.queryUserByParentId(parentUserId);
			
			for(User weiboUser : weiboUsers) {
				if(weiboUser.getUserType().equals(UserType.SINAWEIBO)) {
					request.getSession().setAttribute("authorityLimitInfo", Resources.getString("TryUserAddWeiboLimitCount"));
					response.sendRedirect(WebUtils.getBasepath(request) + "/pages/authorityLimit.jsp");
					return null;
				}
			}
			
		}
		response.sendRedirect(WebUtils.getBasepath(request) + callUrl);
		return null;

	}

	public AuthorityDao getAuthorityDao() {
		return authorityDao;
	}

	public void setAuthorityDao(AuthorityDao authorityDao) {
		this.authorityDao = authorityDao;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public Configuration getConfiguration() {
		return configuration;
	}

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}

}
